# -*- coding: utf-8 -*-

import sys
from PySide6.QtWidgets import *
from PySide6.QtGui import *
from PySide6.QtCore import *
from PySide6.QtPrintSupport import QPrintDialog, QPrinter
import json
import os
os.chdir(os.path.dirname(__file__))

class Winform(QWidget):
    def __init__(self, parent=None, rowData=None):
        super(Winform, self).__init__(parent)
        self.setWindowTitle("QPainter示例")
        self.resize(850, 600)
        
        # 加载配置和数据
        with open('../config/config.json', 'r', encoding="utf-8") as f:
            data = json.load(f)
        
        # 创建一个QLabel来显示QPixmap
        self.label = QLabel(self)
        self.label.setGeometry(QRect(0, 0, 850, 600))  # 设置大小和位置以匹配窗口

        # 绘制QPixmap
        #image = QImage("../images/printMode.png")
        #pixmap = QPixmap.fromImage(image)

        # 创建一个空白的QPixmap
        pixmap = QPixmap(850, 600)
        pixmap.fill(Qt.white)  # 填充白色背景
        painter = QPainter(pixmap)
        # 创建字体对象并设置字体大小
        font = QFont()
        font.setFamily(data.get('font'))  # 设置字体家族
        font.setPointSize(data.get('fontsize'))  # 设置字体大小为12点
        painter.setFont(font)  # 应用字体到绘制器
        painter.drawText(data.get('title_x'), data.get('title_y'), f"{rowData[1][0:25]}")
        painter.drawText(data.get('title_x'), data.get('title_y')+30, f"{rowData[1][25:]}")
        painter.drawText(data.get('date_x'), data.get('date_y'), f"{rowData[0]}")
        painter.drawText(data.get('part_x'), data.get('date_y'), "1")
        painter.drawText(data.get('jm_x'), data.get('date_y'), "普通")
        painter.end()

        # 在QLabel上显示QPixmap
        self.label.setPixmap(pixmap)

        # 添加打印按钮和槽函数
        self.print_button = QPushButton("打印", self)
        self.print_button.clicked.connect(self.print_preview)
        self.print_button.setGeometry(QRect(50, 550, 100, 30))  # 假设按钮在窗口下方
        
        # 添加打印按钮和槽函数
        self.print_button = QPushButton("关闭", self)
        self.print_button.clicked.connect(self.close)
        self.print_button.setGeometry(QRect(550, 550, 100, 30))  # 假设按钮在窗口下方

    def print_preview(self):
        # 创建QPrinter和QPrintDialog
        printer = QPrinter()
        print_dialog = QPrintDialog(printer, self)
        
        # 如果用户点击了打印按钮
        if print_dialog.exec_() == QDialog.Accepted:
            # 使用QPrinter进行绘制
            painter = QPainter(printer)
            painter.drawPixmap(0, 0, self.label.pixmap())
            painter.end()




if __name__ == "__main__":
    app = QApplication(sys.argv)
    form = Winform(None,["sasas","sasa"])
    form.show()
    sys.exit(app.exec())
